package cn.txy.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.txy.base.service.impl.BaseServiceImpl;
import cn.txy.system.domain.Employee;
import cn.txy.system.domain.Logininfo;
import cn.txy.system.mapper.EmployeeMapper;
import cn.txy.system.mapper.LogininfoMapper;
import cn.txy.system.query.EmployeeQuery;
import cn.txy.system.service.EmployeeService;
import cn.txy.system.vo.EmployeeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;


    @Override
    public List<Employee> queryPage(EmployeeQuery employeeQuery) {
        return employeeMapper.queryPage(employeeQuery);
    }

    @Override
    public Integer queryPageCount(EmployeeQuery employeeQuery) {
        return employeeMapper.queryPageCount(employeeQuery);
    }

    @Override
    @Transactional
    public void add(EmployeeVo employeeVo) {
        Employee employee = EmployeeVo.of(employeeVo);
        String salt = RandomUtil.randomString(64);
        String password = SecureUtil.md5(salt + "123456");
        employee.setSalt(salt);
        employee.setPassword(password);
        Logininfo logininfo = new Logininfo();
        logininfo.setSalt(salt);
        logininfo.setPassword(password);
        logininfo.setEmail(employeeVo.getEmail());
        logininfo.setPhone(employeeVo.getPhone());
        logininfo.setType(0);
        logininfo.setDisable(1);
        logininfo.setUsername(employeeVo.getUsername());
        logininfoMapper.add(logininfo);
        employee.setLogininfoId(logininfo.getId());
        this.add(employee);
        Long id = employee.getId();
//        employeeMapper.delRoleByEmployeeId(id);
        employeeMapper.addRoleByEmployeeId(id,employeeVo.getRoles());
    }

    @Override
    public void update(EmployeeVo employeeVo) {

    }
}
